package org.road0329.dlt698.parse;

import com.alibaba.fastjson2.JSONObject;
import org.road0329.dlt698.DataUtils;
import org.road0329.dlt698.axdr.Data;
import org.road0329.dlt698.axdr.GetResult;
import org.road0329.dlt698.bean.FrameData;
import org.road0329.dlt698.tools.ParseTool;
import org.road0329.dlt698.tools.ResultCode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ParseGetResponse {
    public static FrameData parseGetResponseNormal(GetResult getResult) throws Exception {
        FrameData frameData = new FrameData();
        switch (getResult.getChoiceIndex().getValue()) {
            case 0:
                getResult.getDar().encodeAndSave(1000);
                String message = DataUtils.bytesToHexString(getResult.getDar().getDataCode(), 0, getResult.getDar().getDataCode().length);
                frameData.setData(message);
                break;
            case 1:
//                String value = ParseTool.parseData(getResult.getData());
                frameData.setData(getResult);
                break;
        }
        frameData.setCode(ResultCode.SUCCESS.getCode());
        return frameData;
    }

    public static FrameData parseData(Data data) throws Exception {
        Map<String, Object> map = new HashMap<>();
        FrameData frameData = new FrameData();
        switch (data.getChoiceIndex().getValue()) {
            case 1:
                data.getArray().encodeAndSave(1000);
                List<FrameData> list = new ArrayList<>();
                for (int i = 0; i < data.getArray().size(); i++) {
                    list.add(parseData(data.getArray().get(i)));
                }
                map.put(Data.Choice.ARRAY.name(), list);
                frameData.setData(convertTSMapToJSObj(map));
                break;
            case 2:
                break;
            case 3:
                break;
            case 6:
                data.getDoubleLongUnsigned().encodeAndSave(1000);
                map.put(Data.Choice.DOUBLE_LONG_UNSIGNED.name(), DataUtils.bytesToHexString(data.getDoubleLongUnsigned().getDataCode(), 0, data.getDoubleLongUnsigned().getDataCode().length));
                frameData.setData(convertTSMapToJSObj(map));
                break;
        }
        return frameData;
    }

    public static JSONObject convertTSMapToJSObj(Map<String, Object> tsMap) {
        JSONObject jsonObject = new JSONObject();
        for (Map.Entry<String, Object> entry : tsMap.entrySet()) {
            jsonObject.put(entry.getKey(), entry.getValue());
        }
        return jsonObject;
    }
}
